/* 
 * Copyright (C) 2014 Administrator.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301  USA
 */


// order id 生成标记
window.orderId = false;
// 支付完成标记
window.payed = false;
// 收货地址加载标记
window.addressloaded = false;
// 收货地址
window.expressData = {};
// 运费
window.yun = 0;
// lock
window.orderCreateLock = false;

// cache收货地址
function localStorageAddrCache() {
    // localStorage 地址缓存
    // if(!expressData.proviceFirstStageName) window.localStorage.clear();
    if (window.localStorage && window.localStorage.getItem('addr-set') === "1") {
        expressData.userName = storage.getItem('userName');
        expressData.telNumber = storage.getItem('telNumber');
        expressData.Address = storage.getItem('address');
        expressData.addressPostalCode = storage.getItem('PostalCode');
        expressData.proviceFirstStageName = storage.getItem('prov');
        $('#wrp-btn').remove();
        $('#express-name').html(expressData.userName);
        $('#express-person-phone').html(expressData.telNumber);
        $('#express-address').html(expressData.Address);
        // 收货地址加载标记
        window.addressloaded = true;
    }
}

/**
 * 
 * @param {type} res
 * @returns {undefined}
 */
function addAddressCallback(res) {
    // alert(res.err_msg);
    if (res.err_msg === 'edit_address:ok') {
        window.expressData = res;
        expressData.Address = expressData.proviceFirstStageName + expressData.addressCitySecondStageName + expressData.addressCountiesThirdStageName + expressData.addressDetailInfo;
        $('#wrp-btn').remove();
        $('#express-name').html(expressData.userName);
        $('#express-person-phone').html(expressData.telNumber);
        $('#express-address').html(expressData.Address);
        // localStorage address
        if (window.localStorage) {
            var storage = window.localStorage;
            storage.setItem('addr-set', '1');
            storage.setItem('userName', expressData.userName);
            storage.setItem('PostalCode', expressData.addressPostalCode);
            storage.setItem('telNumber', expressData.telNumber);
            storage.setItem('address', expressData.Address);
            storage.setItem('prov', expressData.proviceFirstStageName);
            // alert(expressData.proviceFirstStageName);
        }
        window.addressloaded = true;
        countOrderAmount();
    } else {
        $('#wrp-btn').html('授权失败');
    }
}

/**
 * 加载购物车数据
 * @returns {undefined}
 */
function loadCartData() {
    var jsonData = storage.getItem('cart');
    if (typeof jsonData === 'undefined' || jsonData === '{}' || jsonData === null) {
        fnEmptyCartTip();
    } else {
        Loading.start('#orderDetailsWrapper');
        $.post(shoproot + '?/vProduct/cartData', {
            data: jsonData.toString().replace(/p/g, '')
        }, function(Res) {
            Loading.finish();
            $('#orderDetailsWrapper').html(Res);
            // 计算总数
            $('#order_amount').html('&yen;' + countOrderAmount());
        });
    }
    // 加载收货地址缓存数据
    localStorageAddrCache();
    $('#cart-balance-check').click(function() {
        if (parseFloat($('#cart-balance-pay').text()) > 0) {
            $('#order_amount').html('&yen;' + countOrderAmount(this.checked));
        }
    });
    // WeixinJSBridge.call('hideOptionMenu');
}

/**
 * 删除订单商品
 * @param {type} productId
 * @returns {undefined}
 */
function delFromCart(productId) {
    Cart.del(productId);
    $('#cartsec' + productId).remove();
    if (countOrderAmount() === false) {
        fnEmptyCartTip();
        $('#order_amount').html('&yen;' + 0);
    } else {
        $('#order_amount').html('&yen;' + countOrderAmount());
    }
}

/**
 * 计算订单总数
 * @param {Boolean} balan_pay
 * @returns {Number}
 */
function countOrderAmount(balan_pay) {

    balan_pay = balan_pay | false;

    var ret = 0, tweight = 0;

    if ($('.cartListDesc').length > 0) {
        $('.cartListDesc').each(function(lis, node) {
            var dprice = $('.dprice', node).html();
            var dcount = $('.dcount', node).html();
            tweight += (parseInt($('.dprice', node).attr('data-weight')) * parseInt($('.dprice', node).attr('data-count')));
            ret += (dprice * dcount);
        });
    } else {
        return false;
    }

    if (balan_pay) {
        ret -= parseFloat($('#cart-balance-pay').text());
        if (ret < 0)
            ret = 0;
    }

//    // 计算运费
//    if (ret > 1) {
//        if (tweight <= 1000) {
//            yun = 6.95;
//        } else {
//            tweight -= 1000;
//            var prov = expressData.proviceFirstStageName.replace('省', '');
//            yun = Math.ceil(tweight / 1000);
//            if (prov.match(/广东/g)) {
//                yun *= 2;
//            } else if (prov.match(/福建|上海|浙江|江苏|安徽|湖南|广西|湖北/g)) {
//                yun *= 6;
//            } else if (prov.match(/北京|河南|湖北|河北|天津|山东|四川|重庆/g)) {
//                yun *= 8;
//            } else if (prov.match(/黑龙江|吉林|辽宁|甘肃|内蒙古|新疆/g)) {
//                yun *= 10;
//            }
//            yun += 6.95;
//        }
//    }
//
//    $('#order_yunfei').html('&yen;' + yun);

    return ret + yun;
}

/**
 * 微信支付走起
 * @returns {undefined}
 */
function wepayCall() {

    if (!isLogin()) {
        alert('请先登录');
        location.href = shoproot + '?/Uc/login';
    }

    if (!addressloaded) {
        addAddress();
        return false;
    }

    if ($('#payOn').val() === '1') {
        // 微信支付开通
        if (false === window.addressloaded && typeof WeixinJSBridge !== "undefined") {
            addAddress();
            return false;
        }

        if (storage.getItem('cart') === '{}' || !storage.getItem('cart')) {
            return false;
        }

        // cartData cache
        if (storage.getItem('carthash') && CryptoJS.MD5(storage.getItem('cart')).toString() === storage.getItem('carthash').toString()) {
            window.orderId = storage.getItem('tmporder');
        } else {
            storage.removeItem('tmporder');
            storage.removeItem('carthash');
            window.orderId = false;
        }

        // 生成一个订单
        if (false === orderId) {
            $.post($('#paycallorderurl').val(), {
                addrData: {
                    userName: expressData.userName,
                    telNumber: expressData.telNumber,
                    PostalCode: expressData.addressPostalCode,
                    Address: expressData.Address
                },
                openid: $.cookie('uopenid'),
                cartData: storage.getItem('cart'),
                balancePay: $('#cart-balance-check')[0].checked ? 1 : 0,
                yun: yun,
                leword: $('#pd-form-leword').val()
            }, orderGenhandle);
        } else {
            orderGenhandle(orderId);
        }
    } else {
        // 微信支付未开通，直接下单
        // 生成一个订单
        if (!window.orderCreateLock) {
            window.orderCreateLock = true;
            $.post($('#paycallorderurl').val(), {
                addrData: {
                    userName: expressData.userName,
                    telNumber: expressData.telNumber,
                    PostalCode: expressData.addressPostalCode,
                    Address: expressData.Address
                },
                openid: $.cookie('uopenid'),
                cartData: storage.getItem('cart'),
                balancePay: $('#cart-balance-check')[0].checked ? 1 : 0,
                yun: yun,
                leword: $('#pd-form-leword').val()
            }, function(Id) {
                window.orderCreateLock = false;
                if (parseInt(Id) > 0) {
                    // success 
                    Cart.clear();
                    alert('下单成功！');
                    location.href = shoproot + '?/Uc/orderlist/';
                } else {
                    alert('订单创建失败！');
                }
            });
        }
    }

    // 订单生成回调
    function orderGenhandle(Id) {
        // alert(Id);
        orderId = parseInt(Id) > 0 ? parseInt(Id) : false;
        if (Id > 0 && false === window.payed) {
            $.post($('#paycallurl').val(), {
                orderId: orderId
            }, function($res) {
                // 订单映射
                storage.setItem('carthash', CryptoJS.MD5(storage.getItem('cart')));
                storage.setItem('tmporder', orderId);
                // alert($res);
                var bizPackage = eval('(' + $res + ')');
                WeixinJSBridge.invoke('getBrandWCPayRequest', bizPackage, wepayCallback);
            });
        }
    }
}

/**
 * 微信支付
 * @param {type} res
 * @returns {undefined}
 */
function wepayCallback(res) {
    // alert(res.err_msg);
    switch (res.err_msg) {
        case 'get_brand_wcpay_request:ok':
            // ok
            // 清空购物车
            Cart.clear();
            window.payed = true;
            window.location.href = shoproot + '?/Uc/home';
            break;
        case 'get_brand_wcpay_request:cancel':
            // 取消
            break;
        case 'get_brand_wcpay_request:fail':
            //error
            alert(res.err_code + res.err_desc + res.err_msg);
    }
}

function fnEmptyCartTip() {
    $('#orderDetailsWrapper').html('<div id="cartnothing" onclick="location=\'' + shoproot + '\'">购物车空空如也，去逛逛吧</div>');
}

function pickAddress() {
    $('#addrPick').load(shoproot + '?/Uc/selectOrderAddress/body=true', function() {
        $('.addrw').click(address_item_click);
        $('#addr-add-btn1').click(function() {
            $('#addr-add').show();
            $('#addr-select').hide();
        });
        $('#addr-add-btn-back').click(function() {
            $('#addr-add').hide();
            $('#addr-select').show();
        });
        $('#addr-add-btn').click(address_save);
        $('#addrPick').fadeIn();
    });
}